package com.zjw.core.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 * @description:
 * @author: zhangjiawei
 * @createTime:2022/3/29 16:14
 * @modified by:
 *
 *
 * comparator和comparable的区别: https://blog.csdn.net/diweikang/article/details/80788194
 */
public class ComparatorExample {

    public static void main(String[] args) {
        Artist artist = new Artist(1, "张佳伟", 28);
        Artist artist2 = new Artist(2, "伍鹏", 26);
        Artist artist3 = new Artist(3, "猴年", 27);


        Comparator comparator = createComparator();



        int compare = comparator.compare(artist, artist2);
        int compare2 = comparator.compare(artist, artist3);
        int compare3 = comparator.compare(artist2, artist3);
        System.out.println(compare);
        System.out.println(compare2);
        System.out.println(compare3);


        ArrayList<Artist> arrayList = new ArrayList<>();
        arrayList.add(artist);
        arrayList.add(artist2);
        arrayList.add(artist3);


        //使用最原始的方式，定义comparator比较器，然后比较排序
        Collections.sort(arrayList, comparator);
        System.out.println(arrayList);


        //使用lambda表达式
        Comparator<Artist> comparator4Lambda = Comparator.comparing(Artist::getAge);
        Collections.sort(arrayList, comparator4Lambda);
        System.out.println(arrayList);


        //使用lambda表达式，利用@FunctionInterface的方式定义comparator
        Comparator<Artist> comparator4Lambda2 = (a, b) -> {
            return a.getAge() - b.getAge();
        };
        Collections.sort(arrayList, comparator4Lambda2);
        System.out.println(arrayList);

    }

    public static Comparator<Artist> createComparator() {
        Comparator<Artist> comparator = new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof Artist && o2 instanceof Artist) {
                    Artist artist = (Artist) o1;
                    Artist artist2 = (Artist) o2;
                    return artist.getAge() - artist2.getAge();
                }
                return 0;
            }
        };
        return comparator;
    }
}
